import { ref, computed, resolveDirective } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
// 从 sessionStorage 中获取用户名（如果可用）
const userName = sessionStorage.getItem('userName');
console.log(userName)
export const useCalStore = defineStore('cal', () => {
  //要结算的商品列表
  const calGoodsList = ref([])
  //定义计算属性，存放总价
  const total = computed(() => {
    let sum = 0
    calGoodsList.value.forEach((item) => {
      sum += item.num * item.price
    })
    return sum
  })

  //提交订单
  const submitOrder = async () => {
    //构建订单对象
    const order = {
      userName:userName,
      id: +new Date(),
      orderDate: new Date().toLocaleString(),
      goodsList: calGoodsList.value
    }
    // 发送请求，将订单信息保存到json文件
     await axios.post('http://localhost:3001/orderList',order)
    //发送删除购物车商品的请求
     calGoodsList.value.map((item)=> axios.delete(`http://localhost:3001/cartList/${item.id}`))
 
  }
  

  return { calGoodsList, total, submitOrder }
})
